package com.tzkyzj.tiremanagersystem.utils;

import android.content.Context;
import android.net.Uri;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

public class FileUtils {

    /**
     * 简化的文件获取方法 - 直接从 Uri 创建临时文件
     */
    public static File getFileFromUri(Context context, Uri uri) {
        return createTempFileFromUri(context, uri);
    }

    /**
     * 从 Uri 创建临时文件
     */
    private static File createTempFileFromUri(Context context, Uri uri) {
        InputStream inputStream = null;
        FileOutputStream outputStream = null;

        try {
            inputStream = context.getContentResolver().openInputStream(uri);
            if (inputStream == null) {
                return null;
            }

            // 创建临时文件
            File tempDir = context.getCacheDir();
            File tempFile = File.createTempFile("temp_photo", ".jpg", tempDir);

            outputStream = new FileOutputStream(tempFile);

            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }

            return tempFile;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}